<?php

namespace common\models\project;

use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "hxdc_region_to_lunbo".
 *
 * @property int $id
 * @property int $merchant_id 商户id
 * @property int $region_id region表id
 * @property int $lunbo_id region_lunbo表id
 * @property int $created_at 创建时间
 * @property int $updated_at 最后一次更新时间
 * @property int $status 状态[-1:删除;0:禁用;1启用]
 */
class RegionToLunbo extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'hxdc_region_to_lunbo';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['merchant_id', 'region_id', 'lunbo_id', 'created_at', 'updated_at', 'status', 'sort'], 'integer'],
            [['region_id', 'lunbo_id'], 'required'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'merchant_id' => '商户 ID',
            'region_id' => '地区 ID',
            'lunbo_id' => '轮播图 ID',
            'created_at' => '创建',
            'updated_at' => '更新时间',
            'status' => '状态',
            'sort' => '排序'
        ];
    }

    /**
     * 关联会员
     */
    public function getRegion()
    {
        return $this->hasOne(ProjectRegion::class, ['id' => 'region_id']);
    }

    /**
     * 关联项目
     *
     * @return \yii\db\ActiveQuery
     */
    public function getLunbo()
    {
        return $this->hasMany(RegionLunbo::class,['id' => 'lunbo_id']);
    }

    /**
     * @param bool $insert
     * @return bool
     * @throws \yii\base\Exception
     */
    public function beforeSave($insert)
    {
        if ($this->isNewRecord) {
            $this->created_at = time();
        }
        return parent::beforeSave($insert);
    }
    /**
     * @return array
     */
    public function behaviors()
    {
        $merchant_id = Yii::$app->services->merchant->getId();
        return [
            [
                'class' => TimestampBehavior::class,
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ],
            [
                'class' => BlameableBehavior::class,
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['merchant_id'],
                ],
                'value' => !empty($merchant_id) ? $merchant_id : 0,
            ]
        ];
    }
}
